package com.dl.study.config.jwt;

import com.dl.study.config.propertites.JwtProperties;
import com.dl.study.config.redis.RedisConstant;
import com.dl.study.config.redis.RedisUtil;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @Author: user
 * @Date: 2021/10/22 14:10
 * @Description:
 */
@Component
public class CustomCache<K, V> implements Cache<K, V> {

    @Autowired
    private RedisUtil redis;
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private static CustomCache customCache;

    @PostConstruct
    public void init() {
        customCache = this;
        customCache.jwtProperties = this.jwtProperties;
        customCache.redis = this.redis;
    }

    /**
     * 缓存的key名称获取为shiro:cache:account
     *
     * @param key
     * @return java.lang.String
     * @author Wang926454
     * @date 2018/9/4 18:33
     */
    private String getKey(String key) {
        return RedisConstant.PREFIX_SHIRO_CACHE + JwtUtil.getClaim(key, RedisConstant.ACCOUNT);
    }


    @Override
    public V get(K k) throws CacheException {
        if (!customCache.redis.hasKey(this.getKey(k.toString()))) {
            return null;
        }
        return (V) customCache.redis.get(this.getKey(k.toString()));
    }

    @Override
    public V put(K k, V v) throws CacheException {
        customCache.redis.set(this.getKey(k.toString()), v, customCache.jwtProperties.getShiroCacheExpireTime());
        return v;
    }

    @Override
    public V remove(K k) throws CacheException {
        if (!customCache.redis.hasKey(this.getKey(k.toString()))) {
            return null;
        }
        customCache.redis.del(this.getKey(k.toString()));
        return null;
    }

    /**
     * 清空所有缓存
     */
    @Override
    public void clear() throws CacheException {

    }


    /**
     * 缓存的个数
     */
    @Override
    public int size() {
        return 20;
    }


    /**
     * 获取所有的key
     */
    @Override
    public Set<K> keys() {
//        Set<byte[]> keys = Objects.requireNonNull(redis.).keys("*".getBytes());
//        Set<Object> set = new HashSet<Object>();
//        for (byte[] bs : keys) {
//            set.add(SerializableUtil.unserializable(bs));
//        }
//        return set;
        return null;
    }

    /**
     * 获取所有的value
     */
    @Override
    public Collection<V> values() {
        Set keys = this.keys();
        List<V> values = new ArrayList<>();
        for (Object key : keys) {
            values.add((V) customCache.redis.get(this.getKey(key.toString())));
        }
        return values;
    }
}
